#!/usr/bin/env python3
"""
Bing搜索工具 - 基于fastMCP框架
"""

import logging
from typing import Dict, Any, Optional

import httpx
from pydantic import BaseModel, Field

from config import Config

# 配置日志
logger = logging.getLogger(__name__)

class SearchResult(BaseModel):
    """搜索结果模型"""
    title: str
    url: str
    snippet: str
    display_url: str

# Bing搜索客户端
class BingSearchClient:
    """Bing搜索客户端"""
    
    def __init__(self, api_key: Optional[str], endpoint: str):
        self.api_key = api_key
        self.endpoint = endpoint
        self.session = httpx.AsyncClient()
    
    async def search(self, query: str, count: int = 5) -> Dict[str, Any]:
        """执行Bing搜索"""
        if not self.api_key or Config.MOCK_MODE:
            return self._mock_search_results(query, count)
        
        try:
            headers = {"Ocp-Apim-Subscription-Key": self.api_key}
            params = {
                "q": query,
                "count": count,
                "responseFilter": "webpages",
                "textFormat": "HTML"
            }
            
            response = await self.session.get(self.endpoint, headers=headers, params=params)
            response.raise_for_status()
            return response.json()
            
        except Exception as e:
            logger.error(f"Bing搜索API调用失败: {e}")
            return self._mock_search_results(query, count)
    
    def _mock_search_results(self, query: str, count: int) -> Dict[str, Any]:
        """模拟搜索结果"""
        return {
            "webPages": {
                "value": [
                    {
                        "name": f"搜索结果 {i+1}: {query}",
                        "url": f"https://example{i+1}.com/search/{query.replace(' ', '-')}",
                        "snippet": f"这是关于 '{query}' 的搜索结果 {i+1}。包含相关信息和详细内容，帮助您了解更多关于该主题的信息。",
                        "displayUrl": f"example{i+1}.com"
                    } for i in range(min(count, 5))
                ]
            }
        }

class BingSearchTool:
    def __init__(self):
        self.bing_client = BingSearchClient(Config.BING_SEARCH_API_KEY, Config.BING_SEARCH_ENDPOINT)
    async def bing_search(
        self,
        query: str,
        count: int = 5
    ) -> str:
        """
        使用Bing搜索引擎进行网络搜索
        
        Args:
            query: 搜索关键词
            count: 返回的搜索结果数量
        
        Returns:
            搜索结果列表
        """
        try:
            search_results = await self.bing_client.search(query, count)
            
            results = []
            for item in search_results.get("webPages", {}).get("value", []):
                result = SearchResult(
                    title=item["name"],
                    url=item["url"],
                    snippet=item["snippet"],
                    display_url=item["displayUrl"]
                )
                result_text = f"**{result.title}**\n{result.snippet}\n🔗 {result.url}\n📍 {result.display_url}"
                results.append(result_text)
            
            if results:
                header = f"🔍 Bing搜索结果 (查询: '{query}')\n" + "="*50 + "\n\n"
                return header + "\n\n".join(results)
            else:
                return f"❌ 没有找到关于 '{query}' 的搜索结果。"
                
        except Exception as e:
            logger.error(f"Bing搜索时发生错误: {e}")
            return f"❌ 搜索失败: {str(e)}"



